package cn.lili.common.validation.impl;

import cn.lili.common.utils.StringUtils;
import cn.lili.common.validation.Mobile;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * 电话校验
 * 支持手机号+电话同时校验
 *
 * @author Bulbasaur
 * @since 2021/7/9 1:41 上午
 */
public class MobileValidator implements ConstraintValidator<Mobile, String> {

    private static final Pattern PHONE = Pattern.compile("^1[3-9]\\d{9}$");
    private static final Pattern AREA_MOBILE = Pattern.compile("0\\d{2,3}[-]?\\d{7,8}|0\\d{2,3}\\s?\\d{7,8}|13[0-9]\\d{8}|15[1089]\\d{8}");
    private static final Pattern NO_AREA = Pattern.compile("^[0-9]{5,8}$");
    private static final Pattern FOUR_HUNDRED = Pattern.compile("400-[0-9]{4}-[0-9]{3}$");

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.isEmpty(value)) {
            return true;
        }
        return FOUR_HUNDRED.matcher(value).matches() || AREA_MOBILE.matcher(value).matches() || NO_AREA.matcher(value).matches() || PHONE.matcher(value).matches();

    }


    @Override
    public void initialize(Mobile constraintAnnotation) {

    }

}
